﻿using System;
using System.Diagnostics;
using System.Reflection;

using Castle.Core.Configuration;
using Castle.Facilities.NHibernateIntegration;
using Castle.Facilities.NHibernateIntegration.Builders;

using FluentNHibernate.AutoMap;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

using NHibernate.Cfg;

namespace ScriptManager.Data.Utilities
{
    public class ConfigurationBuilder : IConfigurationBuilder
    {
        public Configuration GetConfiguration(IConfiguration facility)
        {
            try
            {
                var defaultConfigurationBuilder = new DefaultConfigurationBuilder();
                var configuration = defaultConfigurationBuilder.GetConfiguration(facility);

                var autoModel = new AutoPersistenceModel();
                foreach (IConfiguration config in facility.Children["assemblies"].Children)
                {
                    Fluently
                        .Configure(configuration)
                        .Database(MsSqlConfiguration.MsSql2005
                                .ConnectionString(c => c.Is(configuration.Properties["connection.connection_string"]))
                        )
                        .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load(config.Value)))
                        .BuildSessionFactory();
                }

                return configuration;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }
    }
}
